import request from '@/utils/request'
import { json2FormData } from '@/utils'

// 导航
export function navigator() {
  return request({
    method: 'GET',
    url: '/app/v1/tab/getTree'
  })
}

// 查询首页导航类型定义id
export const getHomePageTabDefine = async() => {
  const res = await request({
    method: 'GET',
    url: '/app/v1/v2TabDefine/getHomePageTabDefine'
  })
  return (res.data && res.data.id) || ''
}
// 根据导航id查询自定义导航-目录下所有关联的帮助中心内容id集合
export const getCatalogueIdList = async(v2TabDefineId) => {
  const res = await request({
    method: 'GET',
    url: '/app/v1/v2TabConf/queryCatalogueIdList',
    params: {
      showPlatform: 'mobile',
      v2TabDefineId
    }
  })
  return res.data || []
}

/**
 * 新导航树
 * @param {String} v2TabDefineId 类型定义id
 * @param {String} showPlatform 显示平台：mobile  手机端，pad 平板端， pc
 * */
export function getTabTree(v2TabDefineId) {
  const data = new FormData()
  data.append('v2TabDefineId', v2TabDefineId)
  data.append('showPlatform', 'mobile')
  return request({
    method: 'POST',
    url: '/app/v1/v2TabConf/tabTree',
    // params: { showPlatform: 'mobile' }
    data,
    loading: false
  })
}

// 首页楼层
export function getHomeFloorPage() {
  const data = json2FormData({
    sort: 'sort',
    order: 'asc',
    pageFlag: false,
    filtersRaw: JSON.stringify([{ id: 'referenceId', property: 'referenceId', operator: '=', value: 0 }])
  })
  return request({
    method: 'POST',
    url: '/app/v1/index/page',
    data,
    loading: false
  })
}
// 自定义页面楼层
export function getFullDefinePageById(definePageId) {
  return request({
    method: 'get',
    url: '/app/v1/v2DefinePage/getFullDefinePageById',
    params: { definePageId },
    loading: false
  })
}

// 保存自定义页面浏览记录
export function saveDefinePageBrowsingHistory({ definePageId, definePageName }) {
  return request({
    method: 'POST',
    url: `/app/v1/browsingHistoryDefinePage`,
    data: { definePageId, definePageName, clientCode: 'SAD-APP' }
  })
}

/**
 * 保存自定义导航-目录/分类浏览记录
 * @param {string} tabDefineId 自定义导航ID
 * @param {string} tabDefineName 自定义导航名称
 * @param {string} type 自定义导航类型（自定义导航：1，分类：2，目录：3
*/
export function saveDefineNavigationBrowsingHistory({ tabDefineId, tabDefineName, type }) {
  return request({
    method: 'POST',
    url: `/app/v1/browsingHistoryDefineNavigation`,
    data: { tabDefineId, tabDefineName, type, clientCode: 'SAD-APP' }
  })
}

// 获取空间品类列表
export function getSpaceCategory() {
  /*
  // 20230711 处理品类缓存，注释掉该段代码
   return request({
    method: 'get',
    url: '/app/v1/v2SpaceCategory/'
  }) */
  const storageKey = 'v2SpaceCategory'
  return new Promise((resolve, reject) => {
    const storageData = sessionStorage.getItem(storageKey)
    if (storageData) {
      try {
        const res = JSON.parse(storageData)
        if (res && res.success) {
          resolve(res)
          return
        }
      } catch (error) {
        console.log(error)
      }
    }
    request({
      method: 'get',
      url: '/app/v1/v2SpaceCategory/'
    }).then(res => {
      if (res && res.data && res.success) {
        sessionStorage.setItem(storageKey, JSON.stringify(res))
      }
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}
/** 获取品类分页列表
* @param {number} page
* @param {number} rows
* @param {string} spaceConfId 空间配置id
*/
export function getCategoryPageBySpaceId({ page, rows, spaceConfId, pageFlag = true }) {
  const data = new FormData()
  data.append('page', page)
  data.append('rows', rows)
  data.append('sort', 'sort')
  data.append('order', 'asc')
  data.append('pageFlag', false)// pageFlag
  /*
  // 20230711 处理品类数据缓存，注释掉该段代码
  data.append('filtersRaw', JSON.stringify([
    { id: 'spaceConfId', property: 'spaceConfId', operator: '=', value: spaceConfId }
  ]))
  return request({
    method: 'post',
    url: '/app/v1/v2SpaceCategory/categoryPage',
    data,
    loading: false
  }) */
  const storageKey = 'v2SpaceCategoryPageList'
  return new Promise((resolve, reject) => {
    const storageData = sessionStorage.getItem(storageKey)
    if (storageData) {
      try {
        const tmpObj = JSON.parse(storageData)
        if (tmpObj && tmpObj.success && tmpObj.data && tmpObj.data.records) {
          const records = tmpObj.data.records.filter(v => v.spaceConfId === spaceConfId)
          resolve({
            success: 1,
            data: {
              page,
              rows,
              records,
              total: records.length
            }
          })
          return
        }
      } catch (error) {
        console.log(error)
      }
    }
    request({
      method: 'post',
      url: '/app/v1/v2SpaceCategory/categoryPage',
      data,
      loading: false
    }).then(res => {
      if (res && res.data && res.data.records) {
        sessionStorage.setItem(storageKey, JSON.stringify(res))
        const records = res.data.records.filter(v => v.spaceConfId === spaceConfId)
        resolve({
          success: 1,
          data: {
            page,
            rows,
            records,
            total: records.length
          }
        })
        return
      }
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

// 获取风格系列列表
export function getStyleSeries() {
  /* // 20230711 处理系列缓存，注释掉该段代码
  return request({
    method: 'get',
    url: '/app/v1/v2StyleSeries/'
  }) */
  const storageKey = 'v2StyleSeries'
  return new Promise((resolve, reject) => {
    const storageData = sessionStorage.getItem(storageKey)
    if (storageData) {
      try {
        const res = JSON.parse(storageData)
        if (res && res.success) {
          resolve(res)
          return
        }
      } catch (error) {
        console.log(error)
      }
    }
    request({
      method: 'get',
      url: '/app/v1/v2StyleSeries/'
    }).then(res => {
      if (res && res.data && res.success) {
        sessionStorage.setItem(storageKey, JSON.stringify(res))
      }
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

/** 获取系列分页列表
* @param {number} page
* @param {number} rows
* @param {string} styleConfId 风格配置id
*/
export function getSeriesPageByStyleId({ page, rows, styleConfId, pageFlag = true }) {
  const data = new FormData()
  data.append('page', page)
  data.append('rows', rows)
  data.append('sort', 'sort')
  data.append('order', 'asc')
  data.append('pageFlag', false)// pageFlag
  /*
  // 20230711 处理系列数据缓存，注释掉该段代码
   data.append('filtersRaw', JSON.stringify([
    { id: 'styleConfId', property: 'styleConfId', operator: '=', value: styleConfId }
  ]))
  return request({
      method: 'post',
      url: '/app/v1/v2StyleSeries/seriesPage',
      data,
      loading: false
    })
  */
  const storageKey = 'v2StyleSeriesPageList'
  return new Promise((resolve, reject) => {
    const storageData = sessionStorage.getItem(storageKey)
    if (storageData) {
      try {
        const tmpObj = JSON.parse(storageData)
        if (tmpObj && tmpObj.success && tmpObj.data && tmpObj.data.records) {
          const records = tmpObj.data.records.filter(v => v.styleConfId === styleConfId)
          resolve({
            success: 1,
            data: {
              page,
              rows,
              records,
              total: records.length
            }
          })
          return
        }
      } catch (error) {
        console.log(error)
      }
    }
    request({
      method: 'post',
      url: '/app/v1/v2StyleSeries/seriesPage',
      data,
      loading: false
    }).then(res => {
      if (res && res.data && res.data.records) {
        sessionStorage.setItem(storageKey, JSON.stringify(res))
        const records = res.data.records.filter(v => v.styleConfId === styleConfId)
        resolve({
          success: 1,
          data: {
            page,
            rows,
            records,
            total: records.length
          }
        })
        return
      }
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

// 自定义页面查询SPU商品
export async function gcenterSpuBySku(data) {
  const res = await request({
    method: 'POST',
    url: `/app/v1/search/gcenterProduct`,
    data,
    loading: false
  })
  let list = []
  if (res && res.data && res.data.remoteSolrProductGroupDTOS && res.data.remoteSolrProductGroupDTOS.records) {
    list = res.data.remoteSolrProductGroupDTOS.records
  }
  return list
}

// 自定义页面查询SPU商品
export function queryPersonalCenterEntry() {
  return request({
    method: 'GET',
    url: `/app/v1/personalCenterEntryGroup/`,
    loading: false
  })
}

// 检查楼层是否有查看权限
export const checkPermission = async(floorDetailId) => {
  const res = await request({
    method: 'post',
    url: `/app/v1/index/checkPermission/${floorDetailId}`,
    loading: false
  })
  return res.data === true
}
